package teacher;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.project.institute.DAO.Institute;
import com.project.trac.R;

import core.modules.DatabaseConnector;

public class ViewThread extends Institute implements OnClickListener {
	
	private View layout;
	private TextView spiel;
	private EditText textBox;
	
	private Dialog dialog;
	private AlertDialog.Builder alertDialog;

	private TextView tv_title;
	private TextView tv_thread_body;
	private TextView btn_create;
	
	private int forumID;
	private int cid;
	private String TITLE;
	private String CONTENT;
	private String SECTION;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.student_view_thread);
		setTitle("Upload to " + getSubjectName());
		forumID = getIntent().getExtras().getInt("FORUM_ID");
		
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_thread_body = (TextView) findViewById(R.id.tv_thread_body);
		
		layout = View.inflate(getApplicationContext(), R.layout.generic_dialog_box, null);
		alertDialog = new AlertDialog.Builder(ViewThread.this);
		
		textBox = (EditText) layout.findViewById(R.id.et_dialog_input);
		spiel = (TextView) layout.findViewById(R.id.tv_dialog_spiel);
		spiel.setText("");
		
		textBox.setHeight(140);
		textBox.setLines(20);
		textBox.setMaxLines(50);
		textBox.setSingleLine(false);
		textBox.setGravity(Gravity.LEFT | Gravity.TOP);
		textBox.setFilters(new InputFilter[] { 
			    new InputFilter.LengthFilter(150) // 150 is max length
		});
		
		
		alertDialog.setCancelable(false);
		alertDialog.setPositiveButton("Publish", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (textBox.getText().length() != 0) {
					new AsynchronousTask().execute("reply");
					Toast.makeText(getApplicationContext(), "reply published!", Toast.LENGTH_SHORT).show();
					((ViewGroup) layout.getParent()).removeView(layout);
				} else {
					textBox.setError("must not be empty!");
				}
				
			}});
		
		alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				((ViewGroup) layout.getParent()).removeView(layout);
				dialog.dismiss();
			}});
		
		
		try {
			String item = new AsynchronousTask().execute("initialize").get();
			TITLE = item.subSequence(0, item.indexOf((char) 234)).toString();
			CONTENT = item.subSequence(item.indexOf((char) 234)+1, item.length()).toString();
		} catch (InterruptedException e) {
			DatabaseConnector.Logger(getClass(), "AsynchronousTask - Initialize", e);
		} catch (ExecutionException e) {
			DatabaseConnector.Logger(getClass(), "AsynchronousTask - Initialize", e);
		} catch (NullPointerException e) {
			DatabaseConnector.Logger(getClass(), "AsynchronousTask - Initialize", e);
		}
		
		tv_title.setText(TITLE);
		tv_thread_body.setText(CONTENT);
		
		btn_create = (Button) findViewById(R.id.btn_create);
		btn_create.setOnClickListener(this);
		
	}
	 
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_create:
			
			dialog = alertDialog.setTitle("Compose reply - " + TITLE).setView(layout).create();
			dialog.show();
			
			break;
		}
	}

	private class AsynchronousTask extends AsyncTask<String, String, String> {
		
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected String doInBackground(String... args) {
			try {
				
				if (args[0].equalsIgnoreCase("initialize")) {
					final ResultSet rs = DatabaseConnector.getStatement().executeQuery(
							"SELECT cid, section, title, content, DATE_FORMAT(date_end,'%Y-%b-%d') AS 'end' "
							+ " FROM forum WHERE sid = " + getScheduleID() + " AND id = " + forumID);
					

					while (rs.next()) {
						cid = rs.getInt("cid");
						SECTION = rs.getString("section");
						return  rs.getString("title") + (char) 234 + rs.getString("content");
					}
				}
				
				if (args[0].equalsIgnoreCase("reply")) {
					java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
					
					DatabaseConnector.getConnection().setAutoCommit(false);
					DatabaseConnector.setPreparedStatement("INSERT INTO forum (uid, cid, sid, section, content, replyto_id, replyto_date, isThread) VALUES (?,?,?,?,?,?,?,?)");
					PreparedStatement pps = DatabaseConnector.getPreparedStatement();
					pps.setInt(1, getUserID());
					pps.setInt(2, cid);
					pps.setInt(3, getScheduleID());
					pps.setString(4, SECTION);
					pps.setString(5, textBox.getText().toString());
					pps.setInt(6, forumID);
					pps.setString(7, sdf.format(Calendar.getInstance().getTime()).toString());
					pps.setInt(8, 3);

					pps.executeUpdate();
					pps.close();
				}

		} catch (SQLException e) {
			DatabaseConnector.Logger(getClass(), "doInBackground", e);
		} 

			return null;
		}

		protected void onPostExecute(String postExecute) { }
	}

}